package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.MyThreadLocal;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //查询该动态的评论
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT,page,pagesize);
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }

        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        ArrayList<CommentVo> vos = new ArrayList<>();

        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (comment!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);

                String key ="Comment"+comment.getId().toHexString();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+MyThreadLocal.getUserId();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    //发布评论
    public void saveComments(String movementId, String comment) {
        //1、获取操作用户id
        Long userId = MyThreadLocal.getUserId();
        //2、构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);

    }

    public Integer likeComment(String movementId) {
        Boolean hasLike =movementApi.hasLike(movementId,MyThreadLocal.getUserId(),CommentType.LIKE);
        if (hasLike){
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(MyThreadLocal.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //调用API保存数据到Mongodb
        Integer count = movementApi.save(comment);

        //拼接redis的key，将用户的点赞状态存入redis
        String key = "Comment" + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + MyThreadLocal.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;

    }

    public Integer disLikeComment(String movementId) {
        Boolean hasLike =movementApi.hasLike(movementId,MyThreadLocal.getUserId(),CommentType.LIKE);
        if (!hasLike){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(MyThreadLocal.getUserId());
        //调用API保存数据到Mongodb
        Integer count = movementApi.delete(comment);

        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + MyThreadLocal.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
